package com.farvin.gis;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.farvin.gis.bean.request.AbstractRequestBean;
import com.farvin.gis.bean.response.AbstractResponseBean;
import com.farvin.gis.bean.response.ErrorResponseBean;
import com.farvin.gis.method.AbstractMethod;
import com.farvin.gis.method.MethodFactory;

public class TsjdServlet extends HttpServlet{

	private static MethodFactory methodFactory = MethodFactory.getMethodFactory();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String methodName = req.getParameter("method");
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/plain; charset=utf-8");
		PrintWriter out = resp.getWriter();
		AbstractResponseBean responseBean = null;
		AbstractResponseBean errorRespBean = new ErrorResponseBean();
		
		errorRespBean.setResult(-1);
		if(Tools.notEmpty(methodName)){
			try{
				AbstractMethod<AbstractRequestBean, AbstractResponseBean> method = methodFactory.getMethod(methodName);
				if(method!=null){
					AbstractRequestBean requestBean = methodFactory.getRequestBean(methodName, req);
					requestBean.setRequest(req);
					requestBean.setResponse(resp);
					if(requestBean!=null){
						responseBean = method.doRsponse(requestBean);
					}else{
						errorRespBean.setMsg("请求："+methodName+"对应的实体类尚未注册！");
						responseBean = errorRespBean;
					}
				}else{
					errorRespBean.setMsg("请求："+methodName+"尚未注册！");
					responseBean = errorRespBean;
				}
			}catch (Exception e){
				e.printStackTrace();
				errorRespBean.setMsg("系统异常！");
				responseBean = errorRespBean;
			}
			
		}else{
			errorRespBean.setMsg("缺少请求参数：method");
			responseBean = errorRespBean;
		}
		JSONObject jsonObj = JSONObject.fromObject(responseBean);
		String jsonStr = jsonObj.toString();
		out.write(jsonStr);
		out.flush();
		out.close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}
	
}
